<template>
  <div class="student">
    <!-- 添加 -->
    <el-form :model="studentForm" label-width="90px" style="margin: 10px 0">
      <el-row>
        <el-col :span="8">
          <el-form-item label="学生姓名：">
            <el-input v-model="studentForm.name" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属班级">
            <el-select v-model="studentForm.c_id" placeholder="请选择班级">
              <el-option
                v-for="item in classList"
                :disabled="!item.id"
                :label="`${item.className}--${item.teacherName}`"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="家长电话：">
            <el-input v-model="studentForm.p_phone"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button
            style="margin-left: 20px"
            type="primary"
            @click="addStudent"
            >添加</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="getStudentList"
            >刷新列表数据</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <div class="table_data_btn">
      <el-button type="primary" @click="uploadExcel">上传表格数据</el-button>
      <el-button @click="downloadExcel(null)">下载表格数据</el-button>
      <el-dialog
        v-model="fileDialogVisible"
        title="学生数据文件上传"
        width="50%"
      >
        <el-upload
          class="upload-demo"
          drag
          multiple
          name="students"
          :limit="1"
          :headers="headers"
          :file-list="fileList"
          :on-change="handleChange"
          :on-exceed="
            () => {
              ElMessage.warning(`只允许一次上传一个文件，需要替换文件请先删除下面的文件`);
            }
          "
          :auto-upload="false"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将拖动文件放到这里或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              xlsx/xlx files with a size less than 500kb 即excel文件
            </div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button
              @click="
                () => {
                  fileDialogVisible = false;
                  fileList = [];
                }
              "
              >取消</el-button
            >
            <el-button type="primary" @click="uploadExcel"> 上传 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <el-table
      :data="filterStudentList.slice(handleChangeIndexF, handleChangeIndexL)"
      style="width: 100%"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column label="学号" prop="id" width="120" />
      <el-table-column label="姓名" prop="name" width="180" />
      <el-table-column label="班级" prop="className">
        <template #header>
          <el-select
            v-model="selectClassId"
            placeholder="请选择所属班级"
            style="width: 155px"
            @change="getStudentList"
          >
            <el-option
              v-for="item in classList"
              :label="`${item.className}--${item.teacherName}`"
              :value="item.id"
              :key="item.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="家长电话" prop="p_phone" width="180" />
      <el-table-column label="家长姓名" prop="p_name">
        <template #default="scope">
          {{ scope.row.p_name ?? "未注册" }}</template
        >
      </el-table-column>

      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="small" placeholder="Type to search">
            <template #append>
              <el-select
                v-model="searchSelect"
                placeholder="Select"
                style="width: 85px"
              >
                <el-option label="未注册" value="3" />

                <el-option label="家长姓名" value="2" />
                <el-option label="家长电话" value="1" />
              </el-select>
            </template>
          </el-input>
        </template>
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >Edit</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >Delete</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block" style="margin: 10px 18px">
      <!-- <div class="demonstration">All combined</div> -->
      <el-pagination
        v-model:current-page="pag.currentPage"
        v-model:page-size="pag.pageSize"
        :page-sizes="[2, 1, 10, 15, 20, 40]"
        :small="pag.small"
        :disabled="pag.disabled"
        :background="pag.background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pag.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 对话框 -->
    <el-drawer v-model="drawer" :title="updateStudentForm.name + '-信息'">
      <el-form :model="updateStudentForm" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="updateStudentForm.name" disabled />
        </el-form-item>
        <el-form-item label="家长姓名">
          <el-input v-model="updateStudentForm.p_name" disabled />
        </el-form-item>
        <el-form-item label="家长电话">
          <el-input v-model="updateStudentForm.p_phone" />
        </el-form-item>
        <el-form-item label="班级">
          <el-select
            v-model="updateStudentForm.c_id"
            placeholder="请选择所属班级"
            style="width: 100%"
          >
            <el-option
              v-for="item in classList.slice(1)"
              :label="`${item.className}--${item.teacherName}`"
              :value="item.id"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-button
          type="primary"
          @click="handleUpdate"
          style="position: relative; left: 100px"
        >
          提交</el-button
        >
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { onBeforeMount, reactive, toRefs, computed, unref } from "vue";
import { request } from "../utils/http";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "../utils/auth";
import { Upload } from "@element-plus/icons-vue";
export default {
  setup() {
    let thus = reactive({
      fileDialogVisible: false,
      studentList: [],
      selectClassId: "all",
      search: "",
      searchSelect: "1",
      pag: {
        currentPage: 1,
        pageSize: 10,
        small: null,
        disabled: false,
        background: false,
        total: 0,
        flag: false,
      },
      studentForm: {
        name: null,
        p_phone: null,
        c_id: "",
      },
      updateStudentForm: {},
      classList: [],
      updateIndex: null,
      drawer: false,
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: getToken("token"),
      },
      fileList: [],
    });

    onBeforeMount(() => {
      getStudentList();
      getClassList();
    });
    // 计算显示区域
    const handleChangeIndexL = computed(() => {
      return thus.pag.currentPage * thus.pag.pageSize;
    });
    const handleChangeIndexF = computed(() => {
      return (thus.pag.currentPage - 1) * thus.pag.pageSize;
    });
    // const handelTotal = computed(() => {

    //   return filterStudentList.length;
    // });

    function getStudentList() {
      request.get(`/student/list/${thus.selectClassId}`).then((res) => {
        if (res.status != 200) return ElMessage.error(res.message);
        thus.studentList = res.data;
        thus.pag.total = res.data.length;

        console.log(thus.studentList);
      });
    }
    function getClassList() {
      request.get("/class/list").then((res) => {
        if (res.status != 200) return ElMessage.error(res.message);
        thus.classList = res.data;
        thus.classList.unshift({
          id: "all",
          className: "全部数据",
          teacherName: "All",
        });
      });
    }
    function addStudent() {
      // 表单验证
      request.post("/student/add", { ...thus.studentForm }).then((res) => {
        if (res.status != 200) return ElMessage.error(res.message);
        ElMessage.success(res.message);
        // thus.studentList.unshift({ ...thus.studentForm, id: "生成中" });
        res.data[0] ? thus.studentList.unshift(res.data[0]) : "";
      });
      console.log(thus.studentForm);
    }

    const handleEdit = (index, row) => {
      thus.drawer = true;
      thus.updateStudentForm = JSON.parse(JSON.stringify(row));
      thus.updateIndex = index;
      console.log(index, row);
    };
    const handleDelete = (index, row) => {
      console.log(index, row);
      ElMessageBox.confirm("确认删除改学生吗?", "Warning", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          request.delete(`/student/delete/${row.id}`).then((res) => {
            if (res.status != 200) return ElMessage.error(res.message);
            ElMessage.success(res.message);
            getStudentList();
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };
    const handleUpdate = () => {
      console.log(thus.updateStudentForm);
      request.put("/student/put", thus.updateStudentForm).then(async (res) => {
        if (res.status != 200) {
          return ElMessage.error(res.message);
        }
        console.log(res);
        //  const data = await request.get(`/student/getById/${thus.updateStudentForm.id}`)
        //   console.log(data);
        thus.studentList[thus.updateIndex] = res.data[0];
        ElMessage.success(res.message);
      });
    };

    const filterStudentList = computed(() => {
      thus.pag.flag = !thus.pag.flag;
      console.log("11");
      const res = thus.studentList.filter((data) => {
        // console.log(data);
        if (!thus.search) {
          return !thus.search;
        }

        let flag = false;
        if (thus.searchSelect == "1" || thus.searchSelect == 1) {
          flag =
            data.p_phone &&
            data.p_phone.toLowerCase().includes(thus.search.toLowerCase());
        } else if (thus.searchSelect == "2" || thus.searchSelect == 2) {
          flag =
            data.p_name &&
            data.p_name.toLowerCase().includes(thus.search.toLowerCase());
        } else {
          flag = data.p_name == null || data.p_name == "";
        }
        return flag;
      });
      thus.pag.total = res.length;
      return res;
    });
    // (thus.searchSelect != 1
    //         ? data.p_phone.toLowerCase().includes(thus.search.toLowerCase())
    //         : data.p_name.toLowerCase().includes(thus.search.toLowerCase()))
    //   );

    const handleSizeChange = (val) => {
      console.log(`${val} items per page`);
      thus.pag.pageSize = val;
    };
    const handleCurrentChange = (val) => {
      console.log(`current page: ${val}`);
      thus.pag.currentPage = val;
    };

    // 下载表格
    const downloadExcel = (id) => {
      console.log("id" + id);
      request({
        url: `/student/fileGet/${id}`,
        type: "get",
        responseType: "blob",
      }).then((res) => {
        console.log(res);
        download(res.data, res.headers["filename"]);
      });
    };
    function download(data, filename) {
      var blob1 = new Blob([data], {
        type: "application/vnd.ms-excel;charset=utf-8",
      });
      console.log(blob1);
      const tmpLink = document.createElement("a");
      const objectUrl = URL.createObjectURL(blob1);
      tmpLink.href = objectUrl;
      tmpLink.download = filename;
      document.body.appendChild(tmpLink);
      tmpLink.click();
      document.body.removeChild(tmpLink);
      URL.revokeObjectURL(objectUrl);
    }

    // 上传表格
    const uploadExcel = (e) => {
      if (!thus.fileDialogVisible) {
        thus.fileDialogVisible = true;
      } else {
        console.log(e);
        var param = new FormData();
        thus.fileList.forEach((val, index) => {
          console.log(val, index);
          param.append("students", val.raw);
        });

        request.post("/student/fileAdd", param).then((res) => {
          console.log(res);
          if(res.status===200){
            ElMessage.success(res.message)
          }else{
            ElMessage.error(res.message)

          }
        });
      }
    };

    function handleChange(file, fileList) {
      //文件数量改变
      console.log(file, fileList);
      thus.fileList = fileList;
    }
    return {
      ...toRefs(thus),
      filterStudentList,
      handleSizeChange,
      handleCurrentChange,
      handleChangeIndexF,
      handleChangeIndexL,
      addStudent,
      getStudentList,
      handleDelete,
      handleEdit,
      handleUpdate,
      downloadExcel,
      uploadExcel,
      handleChange,
      ElMessage,
      Upload,
    };
  },
};
</script>

<style lang="less" scoped>
.table_data_btn {
  display: flex;
  flex-direction: column;
  width: 150px;
  .el-button {
    margin: 0;
    margin-bottom: 10px;
  }
  position: absolute;
  right: 100px;
  top: 32px;
}
</style>